import React, { useState } from 'react';
import {
  Table,
  Button,
  Space,
  Avatar,
  Tag,
  Modal,
  message,
  Form,
  Input,
  Select,
  Card,
  Row,
  Col,
  Switch,
  DatePicker,
  Tooltip,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  UserOutlined,
  LockOutlined,
  UnlockOutlined,
  CrownOutlined,
} from '@ant-design/icons';
import { useTable } from '@/hooks/useTable';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import adminApi from '@/api/admin-api';

const { Option } = Select;
const { confirm } = Modal;
const { RangePicker } = DatePicker;

interface UserItem {
  id: number;
  username: string;
  email: string;
  nickname?: string;
  avatar?: string;
  phone?: string;
  status: 'active' | 'inactive';
  last_login_at?: string;
  created_at: string;
  updated_at: string;
}

interface SearchForm {
  keyword?: string;
  status?: 'active' | 'inactive';
  date_range?: [dayjs.Dayjs, dayjs.Dayjs];
}

interface UserForm {
  username: string;
  email: string;
  nickname?: string;
  phone?: string;
  status: 'active' | 'inactive';
}

const UserList: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [modalForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<SearchForm>({});
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<UserItem | null>(null);
  const [modalLoading, setModalLoading] = useState(false);

  // 获取用户列表
  const fetchUsers = async (params: any) => {
    try {
      const response = await adminApi.userManagement.adminUsers({
        page: params.current || 1,
        page_size: params.pageSize || 20,
        keyword: params.keyword,
        status: params.status,
      });
      
      return {
        list: response.data || [],
        total: response.total || 0,
      };
    } catch (error) {
      message.error('获取用户列表失败');
      return {
        list: [],
        total: 0,
      };
    }
  };

  const { data, loading, pagination, refresh, handleTableChange, handleSearch } = useTable({
    fetchData: fetchUsers,
    searchParams,
  });

  // 表格列配置
  const columns: ColumnsType<UserItem> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户信息',
      key: 'user_info',
      width: 200,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar
            size={40}
            src={record.avatar}
            icon={<UserOutlined />}
            style={{ marginRight: 12 }}
          />
          <div>
            <div style={{ fontWeight: 500 }}>{record.nickname || record.username}</div>
            <div style={{ fontSize: 12, color: '#666' }}>@{record.username}</div>
          </div>
        </div>
      ),
    },
    {
      title: '联系方式',
      key: 'contact',
      width: 180,
      render: (_, record) => (
        <div>
          <div style={{ fontSize: 12 }}>{record.email}</div>
          {record.phone && (
            <div style={{ fontSize: 12, color: '#666' }}>{record.phone}</div>
          )}
        </div>
      ),
    },
    {
      title: '最后登录',
      dataIndex: 'last_login_at',
      key: 'last_login_at',
      width: 150,
      render: (lastLogin: string) => (
        lastLogin ? dayjs(lastLogin).format('YYYY-MM-DD HH:mm') : '从未登录'
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'success' : 'error'}>
          {status === 'active' ? '正常' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '注册时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={record.status === 1 ? <LockOutlined /> : <UnlockOutlined />}
            onClick={() => handleToggleStatus(record)}
          >
            {record.status === 1 ? '禁用' : '启用'}
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 搜索处理
  const onSearch = (values: SearchForm) => {
    const params = { ...values };
    if (values.date_range) {
      params.start_date = values.date_range[0].format('YYYY-MM-DD');
      params.end_date = values.date_range[1].format('YYYY-MM-DD');
      delete params.date_range;
    }
    setSearchParams(params);
    handleSearch(params);
  };

  // 重置搜索
  const onReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    handleSearch({});
  };

  // 打开创建/编辑模态框
  const handleCreate = () => {
    setEditingUser(null);
    modalForm.resetFields();
    modalForm.setFieldsValue({
      status: 'active',
    });
    setModalVisible(true);
  };

  const handleEdit = (user: UserItem) => {
    setEditingUser(user);
    modalForm.setFieldsValue({
      username: user.username,
      email: user.email,
      nickname: user.nickname,
      phone: user.phone,
      status: user.status,
    });
    setModalVisible(true);
  };

  // 提交表单
  const handleModalSubmit = async (values: UserForm) => {
    setModalLoading(true);
    try {
      if (editingUser) {
        // 更新用户
        await adminApi.userManagement.adminUsersUpdate(editingUser.id, values);
        message.success('用户更新成功');
      } else {
        // 创建用户
        await adminApi.userManagement.adminUsersCreate(values);
        message.success('用户创建成功');
      }
      
      setModalVisible(false);
      refresh();
    } catch (error) {
      message.error('操作失败，请重试');
    } finally {
      setModalLoading(false);
    }
  };

  // 切换用户状态
  const handleToggleStatus = (user: UserItem) => {
    const action = user.status === 'active' ? '禁用' : '启用';
    const newStatus = user.status === 'active' ? 'inactive' : 'active';
    confirm({
      title: `确认${action}用户`,
      content: `确定要${action}用户 "${user.nickname || user.username}" 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await adminApi.userManagement.adminUsersUpdate(user.id, { status: newStatus });
          message.success(`${action}成功`);
          refresh();
        } catch (error) {
          message.error(`${action}失败`);
        }
      },
    });
  };

  // 删除处理
  const handleDelete = (id: number) => {
    confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？删除后用户的所有数据将无法恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await adminApi.userManagement.adminUsersDelete(id);
          message.success('删除成功');
          refresh();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  return (
    <div>
      {/* 搜索表单 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={onSearch}
          style={{ marginBottom: 16 }}
        >
          <Row gutter={[16, 16]} style={{ width: '100%' }}>
            <Col xs={24} sm={12} md={6}>
              <Form.Item name="keyword" label="关键词">
                <Input placeholder="搜索用户名/昵称/邮箱" allowClear />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="选择状态" allowClear>
                  <Option value="active">正常</Option>
                  <Option value="inactive">禁用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Form.Item name="gender" label="性别">
                <Select placeholder="选择性别" allowClear>
                  <Option value={1}>男</Option>
                  <Option value={2}>女</Option>
                  <Option value={0}>未知</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="date_range" label="注册时间">
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button onClick={onReset}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 操作按钮和表格 */}
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreate}
            >
              新建用户
            </Button>
            <Button icon={<ReloadOutlined />} onClick={refresh}>
              刷新
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          rowKey="id"
          scroll={{ x: 1400 }}
        />
      </Card>

      {/* 创建/编辑模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '创建用户'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form
          form={modalForm}
          layout="vertical"
          onFinish={handleModalSubmit}
        >
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, max: 20, message: '用户名长度在3-20个字符之间' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
                ]}
              >
                <Input placeholder="请输入用户名" disabled={!!editingUser} />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                name="nickname"
                label="昵称"
                rules={[
                  { min: 1, max: 20, message: '昵称长度在1-20个字符之间' },
                ]}
              >
                <Input placeholder="请输入昵称（可选）" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
                ]}
              >
                <Input placeholder="请输入手机号（可选）" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="active">正常</Option>
                  <Option value="inactive">禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <div style={{ textAlign: 'right', marginTop: 24 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={modalLoading}
              >
                {editingUser ? '保存' : '创建'}
              </Button>
            </Space>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default UserList;